package com.baomidou.ant.controller;

import com.baomidou.ant.common.Result;
import com.baomidou.ant.entity.*;
import com.baomidou.ant.kingdee.service.KingdeeService;
import com.baomidou.ant.service.*;
import com.baomidou.ant.utils.MyListUtil;
import com.baomidou.ant.utils.MyStringUtil;
import com.baomidou.ant.vo.request.*;
import com.baomidou.ant.vo.response.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;

import java.util.List;
import java.util.Objects;
import java.util.StringJoiner;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2022-03-18
 */
@RestController
@RequestMapping("/parent-order")
public class ParentOrderController {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IParentOrderService parentOrderService;
    @Autowired
    private IWorkOrderService workOrderService;
    @Autowired
    private IProcessInfoService processInfoService;
    @Autowired
    private IPinLibraryService pinLibraryService;
    @Autowired
    private ISysDeptService deptService;

    //新增接口
    @PostMapping("/save")
    @ApiOperation("新增工单接口")
    public Result save(@RequestBody RequestSaveOrderVo requestSaveOrderVo){
        SysUser sysUser=userService.getById(requestSaveOrderVo.getUserId());
        //普通操作员不允许操作
        if(Objects.equals(sysUser.getType(), "2")){
            return Result.getFailure().setMsg("权限不足!");
        }
        if(Objects.equals(parentOrderService.saveOrder(requestSaveOrderVo), "200")) {
            return Result.getSuccess().setMsg("新增成功!");
        }else if(Objects.equals(parentOrderService.saveOrder(requestSaveOrderVo), "404")){
            return Result.getFailure().setMsg("新增失败! \n" +
                    "Error:请确认是否指派人员");
        }else if(Objects.equals(parentOrderService.saveOrder(requestSaveOrderVo), "300")){
            return Result.getFailure().setMsg("新增失败! \n" +
                    "Error:已存在相同工单号");
        }else if(Objects.equals(parentOrderService.saveOrder(requestSaveOrderVo), "400")){
            return Result.getFailure().setMsg("新增失败! \n" +
                    "Error:工序选择错误或顺序错误,请确认选择的工序是否为该产品的正确生产工序！");
        }else
            return Result.getFailure().setMsg("新增失败! \n" +
                    "Error:保存时发生错误");
    }

    //新增接口
    @PostMapping("/listParent")
    public Result listParent(@RequestBody RequestListParentVo vo){
        IPage<ResponseParentOrderVo> iPage=parentOrderService.list(vo);
        return Result.getSuccess().setData(iPage);
    }

    //删除接口
    @DeleteMapping("/delete/{lotNo}")
    public Result delete(@PathVariable String lotNo){
        ParentOrder parentOrder=parentOrderService.queryByLogNo(lotNo);
        if(parentOrderService.removeById(parentOrder)){
            //子工单删除
            QueryWrapper<WorkOrder> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("parent_id",parentOrder.getId());
            workOrderService.remove(queryWrapper);
            //审核记录和上报记录查询
            return Result.getSuccess().setMsg("删除成功");
        }else{
            return Result.getFailure().setMsg("删除失败");
        }
    }

    //编辑时展示
    @GetMapping("/getParentInfo/{lotNo}")
    public Result getParentInfo(@PathVariable String lotNo){
        ParentOrder parentOrder=parentOrderService.queryByLogNo(lotNo);
        ResponseParentInfoVo vo=new ResponseParentInfoVo();
        BeanUtils.copyProperties(parentOrder,vo);
        vo.setPinName(pinLibraryService.getById(parentOrder.getPinId()).getPinName());
        return Result.getSuccess().setData(vo);
    }

    //编辑接口
    @PostMapping("/update")
    public Result update(@RequestBody RequestUpdateParentVo vo){
        if(Objects.equals(parentOrderService.updateParent(vo), "300")){
            return Result.getFailure().setMsg("失败！已经存在相同的LotNo！");
        }
        if(Objects.equals(parentOrderService.updateParent(vo), "200")){
            return Result.getSuccess().setMsg("保存成功！正在更新子工单...");
        }else
            return Result.getFailure().setMsg("保存失败！");
    }

    //详情时展示
    @GetMapping("/listParentInfo/{lotNo}")
    public Result listParentInfo(@PathVariable String lotNo){
        ParentOrder parentOrder=parentOrderService.queryByLogNo(lotNo);
        ResponseListParentInfoVo vo=new ResponseListParentInfoVo();
        BeanUtils.copyProperties(parentOrder,vo);
        PinLibrary pinLibrary=pinLibraryService.getById(parentOrder.getPinId());
        vo.setPinName(pinLibrary.getPinName());
        int[] ids= MyStringUtil.toInt(parentOrder.getProcess());
        String[] names =new String[ids.length];
        for(int i=0;i<ids.length;i++){
            names[i]=processInfoService.getById(ids[i]).getProcessName();
        }
        String processName=MyStringUtil.strToString(names);
        vo.setProcessName(processName);
        return Result.getSuccess().setData(vo);
    }

    //详情时展示统计图数据
    @GetMapping("/getChartData/{lotNo}")
    public Result getChartData(@PathVariable String lotNo){
        ParentOrder parentOrder=parentOrderService.queryByLogNo(lotNo);
        ResponseChartDataVo vo=new ResponseChartDataVo();
        vo.setOver(parentOrder.isOver());
        vo.setAmount(parentOrder.getAmount());
        vo.setBadAmount(parentOrder.getBadAmount());
        vo.setMissingAmount(parentOrder.getTotalAmount()-parentOrder.getAmount()-parentOrder.getBadAmount());
        if(parentOrder.getAmount()+parentOrder.getBadAmount()==0){
            vo.setNowPassRate("0");
        }else {
            double rate = ((double) parentOrder.getAmount() / (double) (parentOrder.getAmount() + parentOrder.getBadAmount())) * 100;
            vo.setNowPassRate(String.format("%.2f", rate) + "%");
        }
        return Result.getSuccess().setData(vo);
    }

    //子工单明细查询
    @PostMapping("/listChildOrderInfo")
    public Result listChildOrderInfo(@RequestBody RequestChildOrderVo requestChildOrderVo){
        List<ResponseChildOrderInfoVo> voList=parentOrderService.listChild(requestChildOrderVo);
        return Result.getSuccess().setData(voList);
    }

    //统计报表查询
    @PostMapping("/getChartData")
    public Result getChartData(@RequestBody RequestGetChartDataVo vo){
        QueryWrapper<ParentOrder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("order_dept",vo.getDeptId());
        queryWrapper.eq("lot_no",vo.getLotNo());
        if(ObjectUtils.isEmpty(parentOrderService.getOne(queryWrapper))){
            return Result.getFailure().setMsg("没有查询到该工单信息！请确认工单号是否有误!");
        }else {
            ResponseGetChartDataVo responseGetChartDataVo=parentOrderService.getChartData(vo);
            return Result.getSuccess().setData(responseGetChartDataVo);
        }
    }

    //查询金蝶生产
    @PostMapping("/queryKingdee")
    public Result queryKingdee(@RequestBody RequestQueryKingdeeVo vo){
        //获取部门
        String[] pinNames=pinLibraryService.queryByUserId(vo.getUserId());
        SysUser user=userService.getById(vo.getUserId());
        SysDept dept=deptService.getById(user.getDeptId());
        if(ObjectUtils.isEmpty(dept.getErpId())){
            return Result.getFailure().setMsg("部门信息未统一erp,无法查询erp生产订单,请联系管理员统一部门信息");
        }else {
            List<ResponseKingdeeProductionVo> voList= KingdeeService.QUERY_PRD_MOExecuteDetailRpt(pinNames,dept.getErpId());
            if(voList==null){
                //返回null说明没有产品和erp达成
                return Result.getFailure().setMsg("产品库中没有当前部门的产品或者产品库中的产品没有和ERP达成对应！无法查询出ERP生产订单");
            }else if(voList.size()==0){
                //返回空列表说明没有查询到任何数据
                return Result.getFailure().setMsg("没有从ERP中查询到任何数据.");
            }else {
                return Result.getSuccess().setData(MyListUtil.sortList(voList));
            }
        }
    }

    @PostMapping("/addFromKingdee")
    public Result addFromKingdee(@RequestBody RequestAddOrderFromERPVo requestAddOrderFromERPVo){
        String str=parentOrderService.addFromKingdee(requestAddOrderFromERPVo);
        if(Objects.equals(str, "HAVING_IT")){
            return Result.getFailure().setMsg("系统中存在相同工单号");
        }
        if(Objects.equals(str, "NOT_FOUND_DEPT")){
            return Result.getFailure().setMsg("部门信息获取失败");
        }
        if(Objects.equals(str, "NOT_FOUND_PIN")){
            return Result.getFailure().setMsg("产品信息或取失败");
        }
        if(Objects.equals(str, "ADD_SUCCESS")){
            return Result.getSuccess().setMsg("导入成功！");
        }
        if(Objects.equals(str, "ADD_FAILURE")){
            return Result.getSuccess().setMsg("保存时发生异常！");
        }
        return Result.getSuccess();
    }


}
